﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using STX.Admin.Models.BizDownload;
using STX.Domain;
using STX.Service;

namespace STX.Admin.Controllers
{
    public class BizDownloadController : BasePages1Controller<BizDownload, IndexModel, AddModel, EditModel, QueryModel>
    {
        public BizDownloadService BizDownloadService { get; set; }

        protected override void OnInit(out Func<BaseService<BizDownload>> thisService, out Func<IndexModel> getIndexModelFunc, out Func<AddModel> getAddModelFunc, out Func<int, EditModel> getEditModelFunc)
        {
            thisService = () => BizDownloadService;
            getIndexModelFunc = () => new IndexModel();
            getAddModelFunc = () => new AddModel();
            getEditModelFunc = i =>
            {
                var model = BizDownloadService.FindModelById(i);
                if (model == null)
                {
                    throw new Exception("没有找到数据");
                }
                return new EditModel
                {
                    Id = model.Id,
                    Position = model.Position,
                    Title = model.Title,
                    Type = model.Type,
                    Url = model.FileUrl
                };
            };
        }

        protected override long AddHandler(AddModel addModel)
        {
            var model = new BizDownload
            {
                AddTime = DateTime.Now,
                FileUrl = addModel.Url,
                Title = addModel.Title,
                Position = addModel.Position,
                Type = addModel.Type
            };
            return BizDownloadService.Add(model);
        }

        protected override bool EditHandler(EditModel editModel)
        {
            var model = BizDownloadService.FindModelById(editModel.Id);
            if (model == null)
            {
                throw new Exception("没有找到数据");
            }
            model.Title = editModel.Title;
            model.Type = editModel.Type;
            model.Position = editModel.Position;
            model.FileUrl = editModel.Url;
            return BizDownloadService.Update(model);
        }

        protected override IQueryable<BizDownload> QueryHandler(QueryModel queryModel, IQueryable<BizDownload> queryable)
        {
            if (!queryModel.Name.IsNullOrEmpty())
                queryable = queryable.Where(o => o.Title.Contains(queryModel.Name));
            return queryable;
        }
    }
}
